package jt.classic.app.dms;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.system.ISystem;
import jt.classic.system.LicenseAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;
import jt.classic.system.utils.AnnexTool;
import jt.classic.system.wordbook.WordBookUtil;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.limp.basework.console.XSystemConfig;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.mine.Controller;
import org.limp.mine.DataTrimmer;
import org.limp.mine.DateTrimmer;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;


/**
 * 文档管理action
 *
 * @author lvt
 *
 */
public class DmsAction extends LicenseAction {
    /**
     * 获取文件及文件夹集合
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        request.setCharacterEncoding("UTF-8");

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String start = StringTool.checkString(param.get("start"));

        String limit = StringTool.checkString(param.get("limit"));
        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    limit)) + 1);

        // String callback = StringTool.checkString(param.get("callback"));
        String folderid = StringTool.checkString(request.getParameter(
                    "folderid"));
        // 如果文件夹号为空则从根目录开始，此处需要改进因为根目录编号不一定总是1
        folderid = "".equals(folderid) ? "-1" : folderid;
        request.setAttribute("folderid", folderid);

        StringBuffer where_file = new StringBuffer(" ");
        StringBuffer where_folder = new StringBuffer(" ");
        IUser user = ISystem.getSessionUser(request);

        if (!"".equals(folderid) && !"null".equals(folderid) &&
                (folderid != null)) {
            where_file.append(" AND  doc_bvfabryjmq.COL_DIRECTORYID  = '" +
                folderid + "' ");
        }

        if (!"".equals(folderid) && !"null".equals(folderid) &&
                (folderid != null)) {
            where_folder.append(" AND   doc_hgbgodkqxb.COL_PARENTFOLDERID  = '" +
                folderid + "' ");
        }

        String sql_file_2 = "SELECT doc_bvfabryjmq.PK_DOC_BVFABRYJMQ as id," +
            "doc_bvfabryjmq.COL_FILENAME as filename," +
            "doc_bvfabryjmq.COL_FILESIZE as filesize," +
            "isys_object.OBJ_CREATORNAME as creatorname," +
            "isys_object.OBJ_CREATETIME as createtime," +
            "isys_object.OBJ_UPDATETIME as updatetime," +
            "doc_bvfabryjmq.COL_VERSION as version," +
            "doc_bvfabryjmq.COL_STATE as state," +
            "isys_object.OBJ_SUMMARY as summary," +
            "doc_bvfabryjmq.COL_FILETYPE as style," +
            "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
            "FROM doc_bvfabryjmq Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
            "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
            " WHERE " + "isys_object.OBJ_KEY =  'FILEINFO' " +
            where_file.toString() + " and OBJ_CREATORID = '" + user.id() + "'";

        String sql_folder_2 = "SELECT doc_hgbgodkqxb.PK_DOC_HGBGODKQXB as id," +
            "doc_hgbgodkqxb.COL_FOLDERNAME as filename," +
            "doc_hgbgodkqxb.COL_FOLDERSIZE as filesize," +
            "isys_object.OBJ_CREATORNAME as creatorname," +
            "isys_object.OBJ_CREATETIME as createtime," + "'' as updatetime," +
            "'' as version," + "'' as state," +
            "isys_object.OBJ_SUMMARY as summary," + "'' as style," +
            "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
            " FROM isys_object_relation Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
            "Inner Join doc_hgbgodkqxb ON doc_hgbgodkqxb.PK_DOC_HGBGODKQXB = isys_object_relation.OBJ_PKID " +
            "WHERE isys_object.OBJ_KEY =  'FOLDER' " + where_folder.toString() +
            " and OBJ_CREATORID = '" + user.id() + "'";

        String sql1 = "select count(*) from (" + sql_file_2 + " union " +
            sql_folder_2 + ") as u";
        String sql2 = sql_file_2 + " union " + sql_folder_2 +
            "  order by objkey desc,createtime";

        String url = request.getContextPath() + "/app/dms.do?method=list";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            ListRange lr = new ListRange();
            lr.setTotalSize(label.totaldata());
            lr.setList(resultList);
            lr.setSuccess(true);
            outJson(lr, response);

            // request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 获取历史记录列表
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void historyList(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        request.setCharacterEncoding("UTF-8");

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String start = StringTool.checkString(param.get("start"));
        String limit = StringTool.checkString(param.get("limit"));
        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    limit)) + 1);
        String fileid = StringTool.checkString(request.getParameter("fileid"));
        request.setAttribute("fileid", fileid);

        String sql1 = "select count(*) from doc_filehistory where COL_H_FILEID ='" +
            fileid + "'";
        String sql2 = "select * from doc_filehistory where COL_H_FILEID ='" +
            fileid + "'  order by COL_H_VERSION";

        String url = request.getContextPath() +
            "/app/dms.do?method=historyList";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            ListRange lr = new ListRange();
            lr.setTotalSize(label.totaldata());
            lr.setList(resultList);
            lr.setSuccess(true);
            outJson(lr, response);

            // request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 获取历史记录列表
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void eventsList(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        request.setCharacterEncoding("UTF-8");

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String start = StringTool.checkString(param.get("start"));
        String limit = StringTool.checkString(param.get("limit"));
        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    limit)) + 1);
        String fileid = StringTool.checkString(request.getParameter("fileid"));
        String type = StringTool.checkString(request.getParameter("type"));
        request.setAttribute("fileid", fileid);

        String sql1 = "select count(*) from doc_events where FID ='" + fileid +
            "' and TYPE = '" + type + "'";
        String sql2 = "select * from doc_events where FID ='" + fileid +
            "' and TYPE = '" + type + "' order by CTIME";

        String url = request.getContextPath() +
            "/app/dms.do?method=eventsList";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            ListRange lr = new ListRange();
            lr.setTotalSize(label.totaldata());
            lr.setList(resultList);
            lr.setSuccess(true);
            outJson(lr, response);

            // request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 搜索
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void query(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);
        IUser user = ISystem.getSessionUser(request);
        Map param = req.getResource();

        String start = StringTool.checkString(param.get("start"));
        String limit = StringTool.checkString(param.get("limit"));
        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    limit)) + 1);
        String queryText = StringTool.checkString(param.get("queryText"));
        request.setAttribute("queryText", queryText);

        String oname = StringTool.checkString(param.get("oname"));
        String okeyword = StringTool.checkString(param.get("okeyword"));
        String osummary = StringTool.checkString(param.get("osummary"));
        String qcreatetime = StringTool.checkString(param.get("qcreatetime"));
        String qupdatetime = StringTool.checkString(param.get("qupdatetime"));
        String ext = StringTool.checkString(param.get("ext"));

        StringBuffer where = new StringBuffer("");
        StringBuffer fileWhere = new StringBuffer("");

        if (!queryText.equals("") || !oname.equals("")) {
            if (!queryText.equals("")) {
                where.append(" AND  isys_object.OBJ_NAME  like '%" + queryText +
                    "%' ");
            } else if (!oname.equals("")) {
                where.append(" AND  isys_object.OBJ_NAME  like '%" + oname +
                    "%' ");
            }
        }

        if (!osummary.equals("")) {
            where.append(" AND  isys_object.OBJ_SUMMARY  like '%" + osummary +
                "%' ");
        }

        if (!okeyword.equals("")) {
            where.append(" AND  isys_object.OBJ_KEYWORD  like '%" + queryText +
                "%' ");
        }

        if (!qcreatetime.equals("")) {
            where.append(" AND  isys_object.OBJ_CREATETIME  like '%" +
                DateTrimmer.formatDateForVarchar(qcreatetime) + "%' ");
        }

        if (!qupdatetime.equals("")) {
            where.append(" AND  isys_object.OBJ_UPDATETIME  like '%" +
                DateTrimmer.formatDateForVarchar(qupdatetime) + "%' ");
        }

        fileWhere.append(where);

        if (!ext.equals("")) {
            fileWhere.append(" AND doc_bvfabryjmq.COL_FILETYPE = '" + ext +
                "' ");
        }

        String sql_file_2 = "";
        String sql_folder_2 = "";

        if (!where.toString().equals("")) {
            sql_folder_2 = "SELECT doc_hgbgodkqxb.PK_DOC_HGBGODKQXB as id," +
                "doc_hgbgodkqxb.COL_FOLDERNAME as filename," +
                "doc_hgbgodkqxb.COL_FOLDERSIZE as filesize," +
                "isys_object.OBJ_CREATORNAME as creatorname," +
                "isys_object.OBJ_CREATETIME as createtime," +
                "'' as updatetime," + "'' as version," + "'' as state," +
                "doc_hgbgodkqxb.COL_FOLDERSUMMARY as summary," +
                "'' as style," + "isys_object.OBJ_KEY as objkey," +
                "isys_object.ID as objid " +
                " FROM isys_object_relation Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
                "Inner Join doc_hgbgodkqxb ON doc_hgbgodkqxb.PK_DOC_HGBGODKQXB = isys_object_relation.OBJ_PKID " +
                "WHERE  isys_object.OBJ_KEY = 'FOLDER'  " + where.toString() +
                " and OBJ_CREATORID = '" + user.id() + "'";
        }

        if (!fileWhere.toString().equals("")) {
            sql_file_2 = "SELECT doc_bvfabryjmq.PK_DOC_BVFABRYJMQ as id," +
                "doc_bvfabryjmq.COL_FILENAME as filename," +
                "doc_bvfabryjmq.COL_FILESIZE as filesize," +
                "isys_object.OBJ_CREATORNAME as creatorname," +
                "isys_object.OBJ_CREATETIME as createtime," +
                "isys_object.OBJ_UPDATETIME as updatetime," +
                "doc_bvfabryjmq.COL_VERSION as version," +
                "doc_bvfabryjmq.COL_STATE as state," +
                "doc_bvfabryjmq.COL_FILESUMMARY as summary," +
                "doc_bvfabryjmq.COL_FILETYPE as style," +
                "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
                "FROM doc_bvfabryjmq Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
                "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
                " WHERE  isys_object.OBJ_KEY = 'FILEINFO'  " +
                fileWhere.toString() + " and OBJ_CREATORID = '" + user.id() +
                "'";
        }

        if (!sql_file_2.equals("") || !sql_folder_2.equals("")) {
            String sql1 = "select count(*) from (" + sql_file_2 +
                ((ext.equals("") && !sql_folder_2.equals(""))
                ? (" union " + sql_folder_2) : "") + ") as u";
            String sql2 = sql_file_2 +
                ((ext.equals("") && !sql_folder_2.equals(""))
                ? (" union " + sql_folder_2) : "") +
                "  order by objkey desc,createtime";

            String url = request.getContextPath() + "/app/dms.do?method=query";

            try {
                SystemDataSource ds = SystemDataSource.getInstance();
                conn = ds.getConnection();

                QueryJack plus = QueryJackFactory.getInstance()
                                                 .createQueryJack(false);

                // 设置
                plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
                plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
                plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
                plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
                plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
                plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

                List resultList = plus.work();

                Controller controller = plus.getController("form1");

                controller.setType("input");

                Label label = plus.getLabel();

                label.setType("href");

                Object[] result = new Object[4];
                result[0] = resultList;
                result[1] = label;
                result[2] = controller;
                result[3] = pageNO;

                ListRange lr = new ListRange();
                lr.setTotalSize(label.totaldata());
                lr.setList(resultList);
                lr.setSuccess(true);
                outJson(lr, response);

                // request.setAttribute("result", result);
            } catch (Exception ex) {
                ISystem.catchException(request, this, ex);
            } finally {
                SystemDataSource.closeConnection(conn);
            }
        } else {
            ListRange lr = new ListRange();
            lr.setTotalSize(0);
            lr.setList(null);
            lr.setSuccess(true);
            outJson(lr, response);
        }
    }

    /**
     * 获取文件及文件夹集合
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public ActionForward treeNodes(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;
        Connection conn = null;
        request.setCharacterEncoding("UTF-8");

        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String folderid = StringTool.checkString(param.get("folderid"));
        String nodeid = StringTool.checkString(param.get("node"));
        // 如果文件夹号为空则从根目录开始，此处需要改进因为根目录编号不一定总是-1
        folderid = "".equals(folderid) ? "0" : folderid;

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DmsManager dm = new DmsManager(conn);

            // List<TreeNode> nodeList = om.getFolderObjByCreatorId(user.id());
            List<TreeNode> nodeList = dm.getChildrenFolder(user.id(), nodeid);
            Recursion recursion = new Recursion();
            recursion.recursionFn2(nodeList, new TreeNode(nodeid, "0", "0"));
            request.setAttribute("result",
                recursion.modifyStr2(recursion.returnStr2.toString()));
            forward = mapping.findForward("result");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 删除文件及文件夹
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void delete(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String[] isysObjIds = StringTool.checkString(param.get("ids")).split(",");
        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            for (String id : isysObjIds) {
                deleteObj(id, user.id(), conn);
            }

            response.getWriter().print("{success:true}");
            response.getWriter().flush();
        } catch (Exception ex) {
            response.getWriter().print("{success:false}");
            ISystem.catchException(request, this, ex);
        } finally {
            response.getWriter().close();
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 递归删除文件夹及其子文件
     *
     * @param id
     * @param userid
     * @param conn
     */
    private void deleteObj(String id, String userid, Connection conn) {
        try {
            DmsManager dm = new DmsManager(conn);
            ObjectManager om = new ObjectManager(conn);
            ObjectLCManager omlc = new ObjectLCManager(conn);
            List<Map> childrenList = dm.getAllChildren(userid, id);

            if (childrenList.size() > 0) {
                for (Map m : childrenList) {
                    String objid = (String) m.get("objid");
                    deleteObj(objid, userid, conn);
                }

                IObject iobj = omlc.getObjectById(id);
                String objKey = iobj.ikey();

                if ("FOLDER".equals(objKey)) {
                    List l = (List) iobj.icontent().get("DOC_HGBGODKQXB");
                    Map content = (Map) l.get(0);
                    String folderid = (String) content.get("PK_DOC_HGBGODKQXB");
                    dm.deleteRelation(folderid);
                } else if ("FILEINFO".equals(objKey)) {
                    List l = (List) iobj.icontent().get("DOC_BVFABRYJMQ");
                    Map content = (Map) l.get(0);
                    String fileid = (String) content.get("PK_DOC_BVFABRYJMQ");
                    dm.deleteRelation(fileid);
                }

                om.delete(id);
            } else {
                IObject iobj = omlc.getObjectById(id);
                String objKey = iobj.ikey();

                if ("FOLDER".equals(objKey)) {
                    List l = (List) iobj.icontent().get("DOC_HGBGODKQXB");
                    Map content = (Map) l.get(0);
                    String folderid = (String) content.get("PK_DOC_HGBGODKQXB");
                    dm.deleteRelation(folderid);
                    dm.deleteEvents(folderid);
                } else if ("FILEINFO".equals(objKey)) {
                    List l = (List) iobj.icontent().get("DOC_BVFABRYJMQ");
                    Map content = (Map) l.get(0);
                    String fileid = (String) content.get("PK_DOC_BVFABRYJMQ");
                    dm.deleteRelation(fileid);
                    dm.deleteEvents(fileid);
                }

                om.delete(id);
            }

            conn.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 复制文件夹、文件
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public void copy(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        // ActionForward forward = null;
        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String[] isysObjIds = StringTool.checkString(param.get("ids")).split(",");
        String[] isysObjNames = StringTool.checkString(param.get("names"))
                                          .split(",");

        // 目标文件夹id
        String targetId = StringTool.checkString(param.get("targetId"));
        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DmsManager dm = new DmsManager(conn);

            // 是否已存在同名文件夹
            boolean result = false;
            String errormsg = "";

            for (String name : isysObjNames) {
                boolean result_folder = dm.hasSameNameFolder(targetId, name);
                boolean result_file = dm.hasSameNameFile(targetId, name);

                if (result_folder) {
                    errormsg += "文件夹";
                }

                if (result_file) {
                    errormsg += " 文件";
                }

                result = result_folder || result_file;
            }

            if (!result) {
                for (String id : isysObjIds) {
                    copyObj(id, targetId, user, conn);
                }
            }

            conn.commit();

            response.setContentType("text/json; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter()
                    .println("{success:" + !result +
                ",errors:{errormsg:'已存在同名" + errormsg + "'}}");
            response.getWriter().flush();
        } catch (Exception ex) {
            response.getWriter().close();
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 剪切文件夹、文件
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void cut(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String[] isysObjIds = StringTool.checkString(param.get("ids")).split(",");
        String[] isysObjNames = StringTool.checkString(param.get("names"))
                                          .split(",");

        // 目标文件夹id
        String targetId = StringTool.checkString(param.get("targetId"));
        IUser user = ISystem.getSessionUser(request);

        // 是否已存在同名文件夹
        boolean result = false;
        String errormsg = "";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DmsManager dm = new DmsManager(conn);

            for (String name : isysObjNames) {
                boolean result_folder = dm.hasSameNameFolder(targetId, name);
                boolean result_file = dm.hasSameNameFile(targetId, name);

                if (result_folder) {
                    errormsg += "文件夹";
                }

                if (result_file) {
                    errormsg += " 文件";
                }

                result = result_folder || result_file;
            }

            if (!result) {
                ObjectLCManager olcm = new ObjectLCManager(conn);

                ObjectManager om = new ObjectManager(conn);

                for (String id : isysObjIds) {
                    IObject obj = olcm.getObjectById(id);

                    IObject tobj = !targetId.equals("-1") ? om.getObjectShellByRelation("DOC_HGBGODKQXB",
                            targetId) : null;

                    String objkey = obj.ikey();

                    if ("FILEINFO".equals(objkey)) {
                        String fid = (String) ((Map) ((ArrayList) (obj.icontent()
                                                                      .get("DOC_BVFABRYJMQ"))).get(0)).get(
                                "PK_DOC_BVFABRYJMQ");

                        String version = (String) ((Map) ((ArrayList) (obj.icontent()
                                                                          .get("DOC_BVFABRYJMQ"))).get(0)).get(
                                "COL_VERSION");

                        String sql = "UPDATE DOC_BVFABRYJMQ SET COL_DIRECTORYID = " +
                            targetId + " WHERE PK_DOC_BVFABRYJMQ = " + fid;

                        DataTrimmer trimmer = new DataTrimmer(conn);

                        trimmer.execute(sql);

                        dm.insertEvent(fid, user.id(), user.iname(),
                            "剪切至文件夹(" + (tobj != null ? tobj.iname() : "我的文档") + ")", "FILEINFO", version);
                    } else if ("FOLDER".equals(objkey)) {
                        String folderid = (String) ((Map) ((ArrayList) (obj.icontent()
                                                                           .get("DOC_HGBGODKQXB"))).get(0)).get(
                                "PK_DOC_HGBGODKQXB");

                        String sql = "UPDATE DOC_HGBGODKQXB SET COL_PARENTFOLDERID = " +
                            targetId + " WHERE PK_DOC_HGBGODKQXB = " +
                            folderid;

                        DataTrimmer trimmer = new DataTrimmer(conn);

                        trimmer.execute(sql);

                        dm.resetRelation(targetId, folderid, "FOLDER");
                    }
                }
            }

            conn.commit();

            response.setContentType("text/json; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter()
                    .println("{success:" + !result +
                ",errors:{errormsg:'已存在同名" + errormsg + "'}}");
            response.getWriter().flush();
        } catch (Exception ex) {
            response.getWriter().close();
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 递归复制文件夹及其子文件
     *
     * @param 要复制的对象id
     * @param 当前会话user
     * @param conn
     */
    private void copyObj(String id, String targetId, IUser user, Connection conn) {
        try {
            DmsManager dm = new DmsManager(conn);
            ObjectManager om = new ObjectManager(conn);
            ObjectLCManager olcm = new ObjectLCManager(conn);

            IObject obj = olcm.getObjectById(id);
            String objkey = obj.ikey();
            String idColumnName = "";
            String tableName = "";

            if ("FILEINFO".equals(objkey)) {
                ((HashMap) ((ArrayList) (obj.icontent().get("DOC_BVFABRYJMQ"))).get(0)).put("COL_DIRECTORYID",
                    targetId);
                tableName = "DOC_BVFABRYJMQ";
                idColumnName = "PK_DOC_BVFABRYJMQ";
            } else if ("FOLDER".equals(objkey)) {
                ((HashMap) ((ArrayList) (obj.icontent().get("DOC_HGBGODKQXB"))).get(0)).put("COL_PARENTFOLDERID",
                    targetId);
                tableName = "DOC_HGBGODKQXB";
                idColumnName = "PK_DOC_HGBGODKQXB";
            }

            List<Map> childrenList = dm.getAllChildren(user.id(), id);
            String tarId = null;

            if (childrenList.size() > 0) {
                IObject cobj = om.copy(obj.iname(), "", obj, user);

                tarId = (String) ((HashMap) ((ArrayList) (cobj.icontent(cobj.iobject()
                                                                            .itable(tableName)))).get(0)).get(idColumnName);
                dm.insertRelation(targetId, tarId, "FOLDER");	
                for (Map m : childrenList) {
                    String objid = (String) m.get("objid");
                    copyObj(objid, tarId, user, conn);
                }
            } else {
                ((Map) ((List) obj.icontent(obj.iobject().itable(tableName))).get(0)).put("COL_VERSION",
                    "1.0");

                // 复制对象
                IObject cobj = om.copy(obj.iname(), "", obj, user);

                if ("FILEINFO".equals(objkey)) {
                    String version = (String) ((HashMap) ((ArrayList) (obj.icontent(obj.iobject()
                                                                                       .itable(tableName)))).get(0)).get(
                            "COL_VERSION");
                    String fid = (String) ((HashMap) ((ArrayList) (obj.icontent(obj.iobject()
                                                                                   .itable(tableName)))).get(0)).get(idColumnName);
                    String fid_new = (String) ((HashMap) ((ArrayList) (cobj.icontent(cobj.iobject()
                                                                                         .itable(tableName)))).get(0)).get(idColumnName);
                    dm.insertEvent(fid, user.id(), user.iname(), "复制了该文档",
                        "FILEINFO", version);

                    dm.insertEvent(fid_new, user.id(), user.iname(),
                        "创建文档（复制）", "FILEINFO", version);
                } else {
                    String fid = (String) ((HashMap) ((ArrayList) (obj.icontent(obj.iobject()
                                                                                   .itable(tableName)))).get(0)).get(idColumnName);
                    String fid_new = (String) ((HashMap) ((ArrayList) (cobj.icontent(cobj.iobject()
                                                                                         .itable(tableName)))).get(0)).get(idColumnName);
                    dm.insertRelation(targetId, fid_new, "FOLDER");
                    dm.insertEvent(fid, user.id(), user.iname(), "复制文件夹",
                        "FOLDER", "1.00");

                    dm.insertEvent(fid_new, user.id(), user.iname(),
                        "新建文件夹（复制）", "FOLDER", "1.00");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 保存文件夹信息
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public void save(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String folderName = request.getParameter("filename");
        String osummary = request.getParameter("summary");
        String targetId = request.getParameter("COL_PARENTFOLDERID");
        String objid = request.getParameter("objid");
        String id = request.getParameter("id");

        // targetId=(targetId==""?"-1":targetId);
        // org.limp.basework.impl.CommonBean4HSQ cb = new
        // CommonBean4HSQ(request);
        // cb.getResource();
        // request.setCharacterEncoding("UTF-8");
        IUser user = ISystem.getSessionUser(request);
        request.setAttribute("oname", folderName);
        request.setAttribute("ocreatorid", user.id());
        request.setAttribute("ocreatorname", user.iname());
        request.setAttribute("ounitid", user.igroup().id());
        request.setAttribute("ounitname", user.igroup().iname());
        request.setAttribute("ounitnumber", user.igroup().inumber());
        request.setAttribute("pk_doc_hgbgodkqxb", id);
        request.setAttribute("okid", objid);
        request.setAttribute("COL_FOLDERSUMMARY", osummary);
        request.setAttribute("osummary", osummary);
        request.setAttribute("COL_FOLDERNAME", folderName);

        Connection conn = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            ObjectManager om = new ObjectManager(conn);
            DmsManager dm = new DmsManager(conn);
            boolean hasSame = dm.hasSameNameFolder(targetId, folderName);

            if ("".equals(objid) || (objid == null)) {
                // 判断是否已存在同名文件夹
                if (hasSame) {
                    response.setContentType("text/json; charset=UTF-8");
                    response.setHeader("Cache-Control", "no-cache");
                    response.getWriter()
                            .write("{success:false,errors:{errormsg:'已存在同名文件夹'}}");
                    response.getWriter().flush();
                } else {
                    IObject iobj = om.save(request);
                    List objList = om.getObjectContentById(iobj.id(),
                            iobj.iobject(), "DOC_HGBGODKQXB");
                    Map content = (Map) objList.get(0);
                    String folderid = (String) content.get("PK_DOC_HGBGODKQXB");
                    dm.insertRelation(targetId, folderid, "FOLDER");
                    dm.insertEvent(folderid, user.id(), user.iname(), "新建文件夹",
                        "FOLDER", "1.0");
                    response.setContentType("text/json; charset=UTF-8");
                    response.setHeader("Cache-Control", "no-cache");
                    response.getWriter().write("{success:true}");
                    response.getWriter().flush();
                }
            } else {
                om.update(request);
                response.setContentType("text/json; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                response.getWriter().write("{success:true}");
                response.getWriter().flush();
            }

            conn.commit();
        } finally {
            response.getWriter().close();
            SystemDataSource.closeConnection(conn);
        }

        // return forward;
    }

    /**
     * 保存文件信息
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void saveFileInfo(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String osummary = request.getParameter("COL_FILESUMMARY");
        String okid = request.getParameter("okid");
        String okey = request.getParameter("okey");
        request.setAttribute("osummary", osummary);

        // CommonBean4HSQ cbh = new CommonBean4HSQ(request);
        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            ObjectManager om = new ObjectManager(conn);
            // SimpleBean sb = BaseworkUtil.analyzerSimpleBean("DOC_BVFABRYJMQ",
            // cbh);
            //
            // BaseworkUtil util = new BaseworkUtil();
            // util.manualUpdate("DOC_BVFABRYJMQ", sb, conn);
            om.update(request);
            conn.commit();

            response.setContentType("text/json; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().write("{success:true}");
            response.getWriter().flush();
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    public ActionForward getFolderList(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        // ActionForward forward = null;
        Connection conn = null;
        request.setCharacterEncoding("UTF-8");

        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String path = StringTool.checkString(param.get("query"));
        String[] paths = StringUtils.splitPreserveAllTokens(path.substring(1,
                    path.length()), "/");
        int len = paths.length - 1;
        IUser user = ISystem.getSessionUser(request);
        StringBuilder ids = new StringBuilder();
        StringBuilder names = new StringBuilder();
        String parentId = "-1";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DmsManager dm = new DmsManager(conn);

            for (int i = 0; i < len; i++) {
                String name = paths[i];
                List<Map> folderList = dm.getChildrenFolderByName(user.id(),
                        parentId, "=", name);

                if (folderList.isEmpty()) {
                    // 未找到相关的机构
                }

                Map folder = folderList.get(0);
                ids.append("/");
                ids.append((String) folder.get("PK_DOC_HGBGODKQXB"));
                names.append("/");
                names.append((String) folder.get("COL_FOLDERNAME"));
                parentId = (String) folder.get("PK_DOC_HGBGODKQXB");
            }

            ids.append("/");
            names.append("/");

            String name = (paths.length == 0) ? "" : paths[paths.length - 1];
            List<Map> folderList = dm.getChildrenFolderByName(user.id(),
                    parentId, "like", name);
            List result = new ArrayList();

            for (Map m : folderList) {
                result.add(new TreeNode((String) m.get("PK_DOC_HGBGODKQXB"),
                        (String) m.get("COL_FOLDERNAME"),
                        (String) m.get("COL_PARENTFOLDERID"),
                        ids.toString() + m.get("PK_DOC_HGBGODKQXB"),
                        names.toString() + m.get("COL_FOLDERNAME"), false));
            }

            ListRange lr = new ListRange();
            lr.setTotalSize(result.size());
            lr.setList(result);
            lr.setSuccess(true);
            outJson(lr, response);

            // conn.commit();
        } finally {
            response.getWriter().close();
            SystemDataSource.closeConnection(conn);
        }

        return null;
    }

    public ActionForward getFolderByPath(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        Connection conn = null;
        request.setCharacterEncoding("UTF-8");

        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String path = StringTool.checkString(param.get("path"));
        String[] paths = StringUtils.split(path, '/');

        return null;
    }

    /**
     * 获取文件或文件夹的路径
     *
     * @param fid
     */
    public void getPath(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String fId = StringTool.checkString(param.get("fid"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DmsManager dm = new DmsManager(conn);
            Map pathMap = dm.getPath(fId);
            response.setContentType("text/json; charset=UTF-8");
            response.getWriter()
                    .print("{success:true,path:\"" + pathMap.get("fullpath") +
                "\",pathid:\"" + pathMap.get("fullpathId") + "\"}");
            response.getWriter().flush();
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            response.getWriter().close();
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 查看附件
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward download(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;
        Connection conn = null;
        String fk_annex_id = StringTool.checkString(request.getParameter(
                    "fk_annex_id"));
        String fileType = StringTool.checkString(request.getParameter(
                    "fileType"));
        String tableName;
        String sizeColName;

        // 下载最近版本还是历史版本
        if ("latestversion".equals(fileType)) {
            tableName = "DOC_BVFABRYJMQ";
            sizeColName = "COL_FILESIZE";
        } else {
            tableName = "DOC_FILEHISTORY";
            sizeColName = "COL_H_FILESIZE";
        }

        try {
            SystemDataSource ds = SystemDataSource.getInstance();

            conn = ds.getConnection();

            DmsManager dm = new DmsManager(conn);

            String system_annex_id = dm.getAnnexId(fk_annex_id, tableName);

            if ("".equals(system_annex_id)) {
                request.setAttribute("result", "failure");
                forward = mapping.findForward("result");
            } else {
                ObjectLCManager om = new ObjectLCManager(conn);
                IObject obj = om.getObjectByRelation(tableName, fk_annex_id);

                List l = (List) obj.icontent().get(tableName);
                Map content = (Map) l.get(0);
                String size = (String) content.get(sizeColName);

                int fileSize = Integer.parseInt(size);

                int limitSize = Integer.parseInt(WordBookUtil.getWordBookItemName(
                            "downloadfilesize", "max"));

                AnnexTool tool = new AnnexTool(conn);

                if (fileSize <= limitSize) {
                    tool.download(system_annex_id, response);
                } else {
                    AnnexInfo[] annexs = tool.getAnnexs(fk_annex_id, tableName);

                    String userhome = (String) XSystemConfig.config()
                                                            .getProperty("XSYSTEM_USER_HOME");

                    IUser user = ISystem.getSessionUser(request);

                    File downLoadFolder = new File(new File(userhome,
                                user.ilogid()), "downloads");

                    tool.download(annexs[0], downLoadFolder);
                }
            }
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
            request.setAttribute("result", "failure");
            forward = mapping.findForward("result");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return null;
    }

    /**
     * 获取文件属性
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public void getFileInfo(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        String objId = StringTool.checkString(request.getParameter("objId"));
        Map dataMap = new HashMap();
        Map resultMap = new HashMap();

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            IUser user = ISystem.getSessionUser(request);
            conn = ds.getConnection();

            ObjectLCManager omlc = new ObjectLCManager(conn);

            IObject iobj = omlc.getObjectById(objId);

            if (iobj == null) {
                resultMap.put("success", "false");
                resultMap.put("errorMessage", "文档并不存在");
            } else {
                PurviewManager pm = new PurviewManager(conn);

                Map purviewMap = pm.purview4Map(objId, "FILEINFO", user);

                List l = (List) iobj.icontent().get("DOC_BVFABRYJMQ");
                Map content = (Map) l.get(0);

                String parentFolderId = (String) content.get("COL_DIRECTORYID");

                if (!DmsManager.DEFAULT_FOLDER_ID.equals(parentFolderId)) {
                    DmsSharedManager dsm = new DmsSharedManager(conn);

                    if (dsm.InheritPurview(parentFolderId, user)) {
                        Map inheritMap = dsm.InheritPurviewMap(parentFolderId,
                                user);

                        purviewMap.putAll(inheritMap);
                    }
                }

                Set pKeyArray = purviewMap.keySet();

                String createTime = iobj.icreatetime();
                dataMap.put("COL_FILENAME", (String) content.get("COL_FILENAME"));
                dataMap.put("createtime", DateTrimmer.getYMDHMS_LBL(createTime));
                dataMap.put("COL_VERSION", (String) content.get("COL_VERSION"));
                dataMap.put("COL_FILESUMMARY",
                    (String) content.get("COL_FILESUMMARY"));
                dataMap.put("COL_STATE", (String) content.get("COL_STATE"));
                dataMap.put("keySet", pKeyArray);
                resultMap.put("success", "true");
                resultMap.put("data", dataMap);
            }
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        outJson(resultMap, response);
    }

    /**
     * 获取授权对象
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void getPurviewObj(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            String sql = ObjectManager.getObjectPurviewSQL("FILEINFO", user, 0,
                    ">=");

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            String sql1 = "select count(doc_bvfabryjmq.PK_DOC_BVFABRYJMQ) FROM doc_bvfabryjmq Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
                "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
                "Inner Join (" + sql +
                ") C ON isys_object.ID = C.OBJ_ID where isys_object.OBJ_CREATORID <> '" +
                user.id() + "'";

            // + " WHERE isys_object.ID in (" + ids + ")";
            String sql2 = "SELECT doc_bvfabryjmq.PK_DOC_BVFABRYJMQ as id," +
                "doc_bvfabryjmq.COL_FILENAME as filename," +
                "doc_bvfabryjmq.COL_FILESIZE as filesize," +
                "isys_object.OBJ_CREATORNAME as creatorname," +
                "isys_object.OBJ_CREATETIME as createtime," +
                "isys_object.OBJ_UPDATETIME as updatetime," +
                "doc_bvfabryjmq.COL_VERSION as version," +
                "doc_bvfabryjmq.COL_STATE as state," +
                "isys_object.OBJ_SUMMARY as summary," +
                "doc_bvfabryjmq.COL_FILETYPE as style," +
                "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
                "FROM doc_bvfabryjmq Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
                "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
                "Inner Join (" + sql +
                ") C ON isys_object.ID = C.OBJ_ID where isys_object.OBJ_CREATORID <> '" +
                user.id() + "'";
            // + " WHERE isys_object.ID in (" + ids + ")";

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, "");
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            ListRange lr = new ListRange();
            lr.setTotalSize(label.totaldata());
            lr.setList(resultList);
            lr.setSuccess(true);
            outJson(lr, response);
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 根据userid获取用户共享给他人的文件
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void getMyPurviewObj(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String start = StringTool.checkString(param.get("start"));
        String limit = StringTool.checkString(param.get("limit"));
        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    limit)) + 1);

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // String sql1 = "select count(doc_bvfabryjmq.PK_DOC_BVFABRYJMQ)
            // FROM doc_bvfabryjmq " +
            // "Inner Join isys_object_relation ON
            // doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID
            // " +
            // "Inner Join isys_object ON isys_object_relation.ID =
            // isys_object.ID " +
            // "Inner Join isys_purview on isys_purview.OBJ_ID = isys_object.ID
            // " +
            // " where isys_purview.USER_ID = '" + user.id() +
            // "' group by isys_purview.OBJ_ID ";
            String sql_file_2 = "SELECT doc_bvfabryjmq.PK_DOC_BVFABRYJMQ as id," +
                "doc_bvfabryjmq.COL_FILENAME as filename," +
                "doc_bvfabryjmq.COL_FILESIZE as filesize," +
                "isys_object.OBJ_CREATORNAME as creatorname," +
                "isys_object.OBJ_CREATETIME as createtime," +
                "isys_object.OBJ_UPDATETIME as updatetime," +
                "doc_bvfabryjmq.COL_VERSION as version," +
                "doc_bvfabryjmq.COL_STATE as state," +
                "isys_object.OBJ_SUMMARY as summary," +
                "doc_bvfabryjmq.COL_FILETYPE as style," +
                "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
                "FROM doc_bvfabryjmq " +
                "Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
                "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID  " +
                "Inner Join isys_purview on isys_purview.OBJ_ID =  isys_object.ID " +
                " where isys_object.OBJ_KEY =  'FILEINFO' and isys_purview.USER_ID = '" +
                user.id() + "'  group by  isys_purview.OBJ_ID ";

            String sql_folder_2 = "SELECT doc_hgbgodkqxb.PK_DOC_HGBGODKQXB as id," +
                "doc_hgbgodkqxb.COL_FOLDERNAME as filename," +
                "doc_hgbgodkqxb.COL_FOLDERSIZE as filesize," +
                "isys_object.OBJ_CREATORNAME as creatorname," +
                "isys_object.OBJ_CREATETIME as createtime," +
                "isys_object.OBJ_UPDATETIME as updatetime," + "'' as version," +
                "'' as state," + "isys_object.OBJ_SUMMARY as summary," +
                "'' as style," + "isys_object.OBJ_KEY as objkey," +
                "isys_object.ID as objid " + "FROM doc_hgbgodkqxb " +
                "Inner Join isys_object_relation ON doc_hgbgodkqxb.PK_DOC_HGBGODKQXB = isys_object_relation.OBJ_PKID " +
                "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID  " +
                "Inner Join isys_purview on isys_purview.OBJ_ID =  isys_object.ID " +
                " where  isys_object.OBJ_KEY =  'FOLDER' and isys_purview.USER_ID = '" +
                user.id() + "'  group by  isys_purview.OBJ_ID ";

            String sql1 = "select count(*) from (" + sql_file_2 + " union " +
                sql_folder_2 + ") as u";
            String sql2 = sql_file_2 + " union " + sql_folder_2 +
                " order by objkey desc,createtime";

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, "");
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            ListRange lr = new ListRange();
            lr.setTotalSize(label.totaldata());
            lr.setList(resultList);
            lr.setSuccess(true);
            outJson(lr, response);
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    public void outJsonString(String str, HttpServletResponse response) {
        response.setContentType("text/javascript;charset=UTF-8");
        outString(str, response);
    }

    public void outJson(Object obj, HttpServletResponse response) {
        outJsonString(JSONObject.fromObject(obj).toString(), response);
    }

    public void outString(String str, HttpServletResponse response) {
        try {
            PrintWriter out = response.getWriter();
            // System.out.println(str);
            out.write(str);
        } catch (IOException e) {
        }
    }
}
